#!/usr/bin/env python
# encoding: utf-8
"""
catalogmodel.py

Created by AlanYang on 2011-06-21.
Copyright (c) 2011 __MyCompanyName__. All rights reserved.
"""
import time,pymongo

from flask import g
from mongomodel import MongoModel
from application import app

def add_catalog(catalog):
    return 'parent' in catalog and add_sub_catalog(catalog) or add_top_catalog(catalog)
     
def add_top_catalog(catalog):
    assert type(catalog) == dict
    if type(catalog) != dict:
        return False
    return CatalogModel().add_top_catalog(**catalog)
    
def add_sub_catalog(sub):
    if type(sub) != dict:
        return False
    return CatalogModel().add_sub_catalog(**sub)

@app.signal_gettopcatalog.connect
def get_top_catalog(sender):
    return CatalogModel().get_top_catalog()
    
def get_sub_catalog(parent):
    return CatalogModel().get_sub_catalog(parent)

class CatalogModel(MongoModel):
    """
    {'_id':,'name':,'descript':,'creator':,'time':,'parent':,'level':}
    """
    top_level = 0
    def __init__(self):
        if not getattr(g, 'mongo',None):
            g.mongo = pymongo.Connection(app.config['MONGO_HOST'],app.config['MONGO_PORT'])
        MongoModel.__init__(self, g.mongo.freeasker.catalog, '_id', None, 0)
        
    def add_top_catalog(self,**catalog):
        if not 'name' in catalog or not 'creator' in catalog:
            assert 0,'top'
            return False
        catalog['_id'] = catalog['name']
        catalog['level'] = self.top_level
        catalog['time']= time.time()
        return self.save(**catalog)
        
    def add_sub_catalog(self,**sub):
        """
        """
        if not 'name' in sub or not 'parent' in sub or not 'level' in sub or not 'creator' in sub:
            assert 0,'sub'
            return False
        assert sub['level'],'sub catalog level error,value is %s'%sub['level']
        sub['_id'] = sub['name']
        sub['time']= time.time()
        return self.save(**sub)
    
    def get_top_catalog(self):
        where = {'level':self.top_level}
        return self.db.find(where)
        
    def get_sub_catalog(self,parent):
        where = {'parent':parent}
        return self.db.find(where)